import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import moment from 'moment/moment';
import React, { PureComponent } from 'react';

import styles from './index.less';

import { LinkageChartsC, SecondHeaderC, SingleDateC } from '../../../comps';

import { QuickQueryC } from '../../../components';

@Form.create()
class CompareYearC extends PureComponent {
  constructor() {
    super();
    this.state = {
      infoRight: {},
      infoLeft: {},
      radioVal: 'month',
      xAxis1: [],
      xAxis2: [],
      series1: [],
      series2: [],
      yAxis1: [
        { name: '产品数量', gridIndex: 0 },
        { name: '产品规模（亿元）', gridIndex: 1 },
      ],
      yAxis2: [
        { name: '产品数量', gridIndex: 0 },
        { name: '产品规模（亿元）', gridIndex: 1 },
      ],
    };
  }

  getChartsInfo = () => {
    const { dispatch } = this.props;
    const { radioVal, startYear, endYear, tenantId } = this.state;
    dispatch({
      type: 'organProductAnalysisM/getMonthAndDayCharts',
      payload: {
        type: radioVal,
        startYear,
        endYear,
        tenantId,
      },
      callback: (info) => {
        const copySeriesInfo = _.cloneDeep(info.series);
        const copyXAxisInfo = _.cloneDeep(info.xAxis);
        // 左边
        const endData = {};
        // 右边
        const startData = {};

        copySeriesInfo.map((v, i) => {
          // 1 2 代表startDate的产品数量和规模数量
          if (i === 1) {
            startData.productNum = v.data;
          }
          if (i === 3) {
            startData.productScale = v.data;
          }
          // 0 2 代表endDate的产品数量和规模数量
          if (i === 0) {
            endData.productNum = v.data;
          }
          if (i === 2) {
            endData.productScale = v.data;
          }
          if (v.name === `${startYear}年`) {
            v.type = copyXAxisInfo[0].length === 2 ? 'bar' : 'line';
            v.xAxisIndex = [0, 1].includes(i) ? 0 : [3, 2].includes(i) ? 1 : 0;
            v.yAxisIndex = [0, 1].includes(i) ? 0 : [3, 2].includes(i) ? 1 : 0;
          }
          if (v.name === `${endYear}年`) {
            v.type = copyXAxisInfo[0].length === 2 ? 'bar' : 'line';
            v.xAxisIndex = [0, 1].includes(i) ? 0 : [3, 2].includes(i) ? 1 : 0;
            v.yAxisIndex = [0, 1].includes(i) ? 0 : [3, 2].includes(i) ? 1 : 0;
          }
        });
        // 月
        if (copyXAxisInfo[0].length === 2) {
          this.setState({
            infoLeft: startData,
            infoRight: endData,
            xAxis2: copyXAxisInfo.length > 0 ? copyXAxisInfo : [null],
            series2: copySeriesInfo,
          });
        }
        if (copyXAxisInfo[0].length === 5) {
          this.setState({
            infoLeft: startData, // 左边展示
            infoRight: endData, // 右边边展示
            xAxis1: copyXAxisInfo.length > 0 ? copyXAxisInfo : [null],
            series1: copySeriesInfo,
          });
        }
      },
    });
  };

  initDate = (args, form) => {
    const initEndDate = moment(args.endDate).format('YYYY');
    const rightDate = moment(args.endDate).add(-1, 'y').format('YYYY');
    form.setFieldsValue({
      date1: moment(initEndDate),
      date2: moment(rightDate),
    });
    this.setState(
      {
        startYear: rightDate,
        endYear: initEndDate,
        tenantId: args.tenantId ?? [],
      },
      () => {
        this.getChartsInfo();
      },
    );
  };

  componentDidMount() {
    const { args, form } = this.props;
    this.initDate(args, form);
  }

  // eslint-disable-next-line react/no-deprecated
  UNSAFE_componentWillReceiveProps(nextProps) {
    const { args, timestamp, form } = nextProps;
    if (JSON.stringify(args) !== JSON.stringify(this.props.args) || timestamp !== this.props.timestamp) {
      this.initDate(args, form);
    }
  }

  onChangeRadio = (radioVal) => {
    this.setState(
      {
        radioVal,
      },
      () => {
        this.getChartsInfo();
      },
    );
  };

  changeTime = () => {
    const { form } = this.props;
    const date1 = form.getFieldValue('date1');
    const date2 = form.getFieldValue('date2');

    this.setState(
      {
        startYear: moment(date2).format('YYYY'),
        endYear: moment(date1).format('YYYY'),
      },
      () => {
        this.getChartsInfo();
      },
    );
  };

  render() {
    const { radioVal, infoRight, infoLeft, startYear, endYear } = this.state;

    const getMax = (arr) => {
      if (Array.isArray(arr)) {
        return arr.reduce((num1, num2) => (num1 > num2 ? num1 : num2));
      }
      return '--';
    };
    const maxLeftNum = infoLeft.productNum ? getMax(infoLeft.productNum) : '--';
    const maxleftScale = infoLeft.productScale ? getMax(infoLeft.productScale) : '--';
    const maxRightNum = infoRight.productNum ? getMax(infoRight.productNum) : '';
    const maxRightScale = infoRight.productScale ? getMax(infoRight.productScale) : '--';
    return (
      <div className={styles.yearCompar}>
        <SecondHeaderC title='年度对比' />
        <div className={styles.content}>
          <div className={styles.leftContent}>
            <div>对比年份：</div>
            <div className={styles.input}>
              <Form layout='inline'>
                <SingleDateC
                  form={this.props.form} // form对象
                  dataIndex='date1' // Form识别的下拉选项Item ID
                  onChange={(e) => this.changeTime(e, 1)} // 时间变化事件
                  initialValue={undefined}
                  dataType='year'
                />
                <span className={styles.middle}>:</span>
                <SingleDateC
                  form={this.props.form} // form对象
                  dataIndex='date2' // Form识别的下拉选项Item ID
                  onChange={(e) => this.changeTime(e, 2)} // 时间变化事件
                  initialValue={undefined}
                  dataType='year'
                />
              </Form>
            </div>
          </div>
          <div className={styles.quick}>
            <QuickQueryC
              dataSource={[
                {
                  value: 'month',
                  title: '月',
                  tooltip: '统计每月最后一天的产品数量和规模',
                },
                { value: 'day', title: '日' },
              ]}
              initialValue={radioVal}
              onChange={(e) => this.onChangeRadio(e)}
            />
          </div>
        </div>

        <div className={styles.info}>
          <div className={styles.infoContent}>
            <div className={styles.year}>{endYear}年</div>
            <div className={styles.num}>
              <div>
                产品数量峰值为&nbsp;&nbsp;
                <span>{maxRightNum ?? '--'}只</span>
              </div>
              <div>
                产品规模峰值为&nbsp;&nbsp;
                <span>
                  {maxRightScale ?? '--'}
                  亿元
                </span>
              </div>
            </div>
          </div>
          <div className={styles.line} />
          <div className={styles.infoContent}>
            <div className={styles.year}>{startYear}年</div>
            <div className={styles.num}>
              <div>
                产品数量峰值为&nbsp;&nbsp;
                <span>{maxLeftNum ?? '--'}只</span>
              </div>
              <div>
                产品规模峰值为&nbsp;&nbsp;
                <span>
                  {maxleftScale ?? '--'}
                  亿元
                </span>
              </div>
            </div>
          </div>
        </div>
        {/* 月日图 */}
        <div>
          {radioVal === 'month' ? (
            <Spin spinning={this.state.xAxis2.length === 0}>
              <LinkageChartsC
                isMarkPoint={true}
                xAxis={this.state.xAxis2}
                series={this.state.series2}
                yAxis={this.state.yAxis2}
                height='600px'
                barMaxWidth={16}
                dataZoom={true}
                toolTipDataFormat={[
                  (value, item) => (value ? `${value} ${item.axisIndex === 1 ? '亿元' : '只'}` : `${item.axisIndex === 1 ? '--亿元' : '--只'}`),
                  (value, item) => (value ? `${value} ${item.axisIndex === 1 ? '亿元' : '只'}` : `${item.axisIndex === 1 ? '--亿元' : '--只'}`),
                  (value, item) => (value ? `${value} ${item.axisIndex === 1 ? '亿元' : '只'}` : `${item.axisIndex === 1 ? '--亿元' : '--只'}`),
                  (value, item) => (value ? `${value} ${item.axisIndex === 1 ? '亿元' : '只'}` : `${item.axisIndex === 1 ? '--亿元' : '--只'}`),
                ]}
              />
            </Spin>
          ) : (
            <Spin spinning={this.state.xAxis1.length === 0}>
              <LinkageChartsC
                isMarkPoint={true}
                xAxis={this.state.xAxis1}
                series={this.state.series1}
                yAxis={this.state.yAxis1}
                height='600px'
                dataZoom={true}
                toolTipDataFormat={[
                  (value, item) => (value ? `${value} ${item.axisIndex === 1 ? '亿元' : '只'}` : `${item.axisIndex === 1 ? '--亿元' : '--只'}`),
                  (value, item) => (value ? `${value} ${item.axisIndex === 1 ? '亿元' : '只'}` : `${item.axisIndex === 1 ? '--亿元' : '--只'}`),
                  (value, item) => (value ? `${value} ${item.axisIndex === 1 ? '亿元' : '只'}` : `${item.axisIndex === 1 ? '--亿元' : '--只'}`),
                  (value, item) => (value ? `${value} ${item.axisIndex === 1 ? '亿元' : '只'}` : `${item.axisIndex === 1 ? '--亿元' : '--只'}`),
                ]}
              />
            </Spin>
          )}
        </div>
      </div>
    );
  }
}
export default connect(({ organProductAnalysisM }) => ({
  organProductAnalysisM,
}))(CompareYearC);
